package com.tee.web.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;


import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.tee.bean.privilege.PrivilegeGroup;
import com.tee.bean.privilege.SystemPrivilege;
import com.tee.bean.privilege.SystemPrivilegePK;
import com.tee.bean.privilege.User;
import com.tee.utils.SiteUrl;
import com.tee.web.action.privilege.Permission;
import com.tee.web.action.privilege.ValidatePermission;

public class PermissionInterceptor extends AbstractInterceptor {
	
	private static final long serialVersionUID = -782732202409715796L;
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		
		ActionProxy proxy = invocation.getProxy();
		String methodName = proxy.getMethod();
		Object action = proxy.getAction();
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request.getRequestURI().startsWith("/control/main/")) {
			if (!validate(action.getClass(), methodName, request)) {
				ActionContext.getContext().put("message", "您没有执行该操作的权限");
				ActionContext.getContext().put("urladdress",SiteUrl.readUrl("welcome"));
				return "message";
			}
		}
		return invocation.invoke();
	}

	private boolean validate(Class<?> clazz, String methodName,
			HttpServletRequest request) throws NoSuchMethodException {
		Permission permission = ValidatePermission.parsePermission(clazz,methodName,null);
		if (permission != null) {
			SystemPrivilege methodPrivilege = new SystemPrivilege(
					new SystemPrivilegePK(permission.model(), permission.privilegeValue()));
			request = ServletActionContext.getRequest();
			User user = (User) request.getSession().getAttribute("user");
			for (PrivilegeGroup u : user.getGroups()) {
				if (u.getPrivileges().contains(methodPrivilege))
					return true;
			}
			return false;
		}
		return true;
	}

}

